package mamikeji.liaowa.ui.activity.forum;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyForumBean;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.adapter.MyForumAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class MyForumActivity extends BaseActivity {
    private static final String TAG = "MyForumActivity";

    private static final int TAG_FORUM = 1002;
    private static final int TAG_PUBLISH_FORUM = 1004;

    @BindView(R.id.listView_my_forum)
    PullToRefreshListView listViewMyForum;
    @BindView(R.id.ptrlDownRefreshFrameLayout_my_forum)
    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayoutMyForum;
    @BindView(R.id.multiStateView_my_forum)
    MultiStateView multiStateViewMyForum;

    boolean bool_delte = false;

    MyForumAdapter myForumAdapter;

    List<MyForumBean.DataEntity> myForumList = new ArrayList<>();

    /**
     * 当前页数
     */
    private int page = 1;
    /**
     * 总页数
     */
    private int maxPage = 0;

    /**
     * 每页的活动数据集合
     */
    ArrayList<MyForumBean.DataEntity> mList;

    int position_s;
    int fc_id_s;

    private int list_item_num = -1;

    private boolean bool_circle_refresh = false;
    private boolean bool_delete = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_forum);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh) {
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        setTitleName(R.string.my_forum_name);
        setTitleRightImage(R.drawable.icon_shanchunaozhong_n, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**震动服务*/
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(50);//只震动一秒，一次

                myForumAdapter.bool_delete = !myForumAdapter.bool_delete;
                myForumAdapter.notifyDataSetChanged();
            }
        });

        init();
        showDeleteDialog();
    }

    private void init() {
        bool_circle_refresh = false;
        myForumAdapter = new MyForumAdapter(myForumList, this);

        listViewMyForum.getRefreshableView().setAdapter(myForumAdapter);

        listViewMyForum.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!myForumAdapter.bool_delete) {
                    list_item_num = i-1;
                    int num = myForumList.get(i-1).getBrowse_total();
                    myForumList.get(i-1).setBrowse_total(num++);
                    myForumAdapter.notifyDataSetChanged();

                    Intent intent = new Intent(MyForumActivity.this, ForumMSGActivity.class);
                    intent.putExtra("MyForumBean", myForumList.get(i-1));
                    startActivityForResult(intent, TAG_FORUM);
                }
            }
        });

        getMain_ForumData(1, 10);

        multiStateViewMyForum.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getMain_ForumData(1, 10);
                    }
                });

        multiStateViewMyForum.setEmptyText(R.string.my_forum_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(MyForumActivity.this, PublishForumActivity.class), TAG_PUBLISH_FORUM);
            }
        });

        ptrlDownRefreshFrameLayoutMyForum.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listViewMyForum.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getMain_ForumData(1, 10);
            }
        });

        listViewMyForum.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        listViewMyForum.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新数据
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            //上拉加载更多
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (++page >= maxPage) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            listViewMyForum.onRefreshComplete();
                            ForToast.showToast(R.string.error_down_end);
                        }
                    }, 1000);
                } else {
                    getMain_ForumData(page, 10);
                }
            }
        });

        myForumAdapter.setOnItemClickListener(new MyForumAdapter.OnItemClickListener() {
            @Override
            public void onZanClick(int fc_id, int position) {
                getFabulousCircle(position);
            }

            @Override
            public void onMSGClick(int fc_id, int position) {
                Intent mIntent = new Intent(MyForumActivity.this, FriendMSGActivity.class);
                mIntent.putExtra(HttpKey.Friend_MSG_friendcode, myForumList.get(position).getUsercode());
                startActivity(mIntent);
            }

            @Override
            public void onDeleteClick(int fc_id, int position) {
                position_s = position;
                fc_id_s = fc_id;
                dialog_delete.show();
            }
        });
    }

    private Dialog dialog_delete;
    private RelativeLayout relativeLayout_clock_dig_query, relativeLayout_clock_dig_btnerror;

    /**
     * 确认删除
     */
    private void showDeleteDialog() {
        dialog_delete = new Dialog(MyForumActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(MyForumActivity.this).inflate(R.layout.diglog_clock_delete, null);
        dialog_delete.setContentView(inflate);

        relativeLayout_clock_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_query);
        relativeLayout_clock_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_btnerror);

        relativeLayout_clock_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();

                getDelete_ForumData();
            }
        });
        relativeLayout_clock_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();
            }
        });
    }

    /**
     * 获取我的话题数据
     *
     * @param indexpage
     * @param pagesize
     * @return
     */
    public void getMain_ForumData(int indexpage, int pagesize) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_my_current, indexpage + "");
        formMap.put(HttpKey.Forum_my_pagesize, pagesize + "");
        formMap.put(HttpKey.Forum_my_topic_id, "");
        formMap.put(HttpKey.Forum_my_usercode, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.GetMyTopicPage, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMain_ForumData", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MyForumBean bean = new Gson().fromJson(response, MyForumBean.class);

                        mList = new ArrayList<MyForumBean.DataEntity>();
                        mList = (ArrayList<MyForumBean.DataEntity>) bean.getData();

                        if (mList != null && mList.size() > 0) {
                            if (page == 1) {
                                maxPage = bean.getTotal();
                                myForumList.clear();
                                myForumList.addAll(mList);
                                //刷新数据
                                myForumAdapter.setList(myForumList);
                            } else {
                                //加载更多
                                myForumList.addAll(mList);
                                myForumAdapter.notifyDataSetChanged();
                            }
                            multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (page == 1) {
                                multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                        multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 删除话题
     */
    private void getDelete_ForumData() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_delete_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Forum_delete_topic_id, myForumList.get(position_s).getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.DelTopic, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("已删除！");
                        bool_circle_refresh = true;
                        myForumList.remove(position_s);
                        myForumAdapter.notifyDataSetChanged();

                        //用户话题数量
                        int num = ForPreference.getInt(ForContents.USER_forum_num) - 1;
                        //用户话题数量
                        ForPreference.putInt(ForContents.USER_forum_num, num);

                        if (num == 0){
                            multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }else {
                            multiStateViewMyForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousCircle(final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_Praise_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Forum_Praise_topic_id, myForumList.get(position).getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicPraise, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bool_circle_refresh = true;
                        int num = myForumList.get(position).getPraise_total();
                        if (myForumList.get(position).getIs_praise() == 1) {
                            myForumList.get(position).setIs_praise(0);
                            myForumList.get(position).setPraise_total(--num);
                        } else {
                            myForumList.get(position).setIs_praise(1);
                            myForumList.get(position).setPraise_total(++num);
                        }
                        myForumAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_PUBLISH_FORUM) {
                getMain_ForumData(1, 10);
            }
            if (requestCode == TAG_FORUM) {
                ForLog.i(TAG, "1");
                Web_forum_changeBean web_forum_changeBean = (Web_forum_changeBean) data.getSerializableExtra("web_forum_changeBean");

                myForumList.get(list_item_num).setIs_praise(web_forum_changeBean.getZanStatic());
                myForumList.get(list_item_num).setPraise_total(web_forum_changeBean.getZanNum());
                myForumList.get(list_item_num).setMessage_total(web_forum_changeBean.getCommentNum());

                if (web_forum_changeBean.getWebFocusList() != null) {
                    if (web_forum_changeBean.getWebFocusList().size() > 0) {
                        for (int i = 0; i < web_forum_changeBean.getWebFocusList().size(); i++) {
                            for (int j = 0; j < myForumList.size(); j++) {
                                if (web_forum_changeBean.getWebFocusList().get(i).getFollowusercode().
                                        equals(myForumList.get(j).getUsercode())) {
                                    myForumList.get(j).setIs_follow(web_forum_changeBean.getWebFocusList().get(i).getFocusNum());
                                }
                            }
                        }
                    }
                }

                myForumAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (bool_circle_refresh) {
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
